package middlewares

import (
	//   "log"
	"fmt"
	"net"
	"net/http"
	"strings"

	"github.com/gofiber/fiber/v2"
)

func AllRequests(c *fiber.Ctx) error {

	// log.Println("Параметры запроса: ", c.AllParams())
	//Эта ф-ция вызывается при обработке каждого запроса пути /startups/*
	return c.Next()
}

func IPMiddleware(allowedDomains []string) func(*fiber.Ctx) error {

	return func(c *fiber.Ctx) error {
		remoteIP := c.IP()
		names, err := net.LookupAddr(remoteIP)
		if err != nil {
			fmt.Println("Error looking up the host:", err)
			return c.Status(http.StatusInternalServerError).JSON(fiber.Map{
				"error": "Failed to look up the host",
			})
		}

		for _, name := range names {
			fmt.Println(name)
			for _, domain := range allowedDomains {
				if strings.TrimSpace(name) == strings.TrimSpace(domain) {
					return c.Next()
				}
			}
		}

		return c.Status(http.StatusForbidden).JSON(fiber.Map{
			"error": "Access denied",
		})
	}
}

func GitMiddleware() func(*fiber.Ctx) error {
	return func(c *fiber.Ctx) error {
		// fmt.Println(c.Get("X-GitHub-Event")) //debug
		if ok := c.Get("X-GitHub-Event", ""); ok != "" {
			return c.Next()
		}

		return c.Status(http.StatusForbidden).JSON(fiber.Map{
			"error": "Access denied",
		})
	}
}
